import moment from 'moment'

/**
 * 时间辅助工具库
 */

/* ---------- 基础时间处理函数 ---------- */

/**
 * 将时间向下取整为6分钟的倍数
 */
export function floorTo6min(time) {
  let now_time = moment(time).format('YYYY-MM-DD HH')
  let minutes = moment(time).format('mm')
  let renderminutes = Math.floor(minutes / 6) * 6
  
  return `${now_time}:${renderminutes.toString().padStart(2, '0')}`
}

/**
 * 判断指定时间加上分钟数后是否为整点
 */
export function isHour(startTime, minutesToAdd, isAdd = true) {
  let initialDateTime = moment(startTime, 'YYYY-MM-DD HH:mm:ss')
  let newDateTime = isAdd ? initialDateTime.add(minutesToAdd, 'minutes') : initialDateTime.subtract(minutesToAdd, 'minutes')
  return newDateTime.minute() === 0 && newDateTime.second() === 0 ? 1 : 0
}

/**
 * 判断指定时间加上小时数后是否为当天的0点
 */
export function isDay(startTime, hoursToAdd, isAdd = true) {
  let initialDateTime = moment(startTime, 'YYYY-MM-DD HH')
  let newDateTime = isAdd ? initialDateTime.add(hoursToAdd, 'hours') : initialDateTime.subtract(hoursToAdd, 'hours')
  let midnight = moment(newDateTime).startOf('day')
  return newDateTime.format('YYYY-MM-DD HH') === midnight.format('YYYY-MM-DD HH') ? 1 : 0
}

/**
 * 判断指定时间加上天数后是否为当月第一天
 */
export function isMonth(startTime, daysToAdd) {
  let initialDateTime = moment(startTime, 'YYYY-MM-DD')
  let newDateTime = initialDateTime.add(daysToAdd, 'days')
  let firstDay = moment(newDateTime).startOf('month')
  return newDateTime.format('YYYY-MM-DD') === firstDay.format('YYYY-MM-DD') ? 1 : 0
}

/**
 * 根据时间步长类型计算一个小格代表的时间
 */
export function calcSteps(step_str) {
  const stepMap = {
    'step_6min': 6,
    'step_10min': 10,
    'step_1h': 1,
    'step_3h': 1,
    'step_6h': 1,
    'step_12h': 1,
    'step_24h': 1
  }
  
  return stepMap[step_str] || 1
}

/**
 * 计算右侧标签文本
 */
export function calcMarksRightLabel(step_str, startTime, isTime, i) {
  if (step_str === 'step_1day') {
    return isTime ? 
      moment(startTime).add(i, 'days').format('YYYY-MM-DD') : 
      moment(startTime).add(i, 'days').format('YYYY-MM')
  }
  return ''
}

/**
 * 根据模式、时间间隔和当前时间计算初始时间
 */
export function getStartTime(tabOption, step_type, now_time) {
  if (tabOption === '历史' && step_type === 'step_6min') {
    return moment(floorTo6min(now_time)).subtract(12, 'hours').format('YYYY-MM-DD HH:mm:ss')
  }
  return now_time
}

/**
 * 计算向左的下一个时间轴的初始时间
 */
export function getLeftStartTime(step_type, endTime) {
  if (step_type === 'step_6min') {
    return moment(endTime).subtract(200 * 6, 'minutes').format('YYYY-MM-DD HH:mm:ss')
  } else if (step_type === 'step_10min') {
    return moment(endTime).subtract(200 * 10, 'minutes').format('YYYY-MM-DD HH:mm:ss')
  }
  return endTime
}

/**
 * 计算向右的下一个时间轴的初始时间
 */
export function getRightStartTime(step_type, endTime) {
  if (step_type === 'step_1day') {
    return moment(endTime).add(1, 'days').format('YYYY-MM-DD')
  }
  return endTime
}

/* ---------- 刻度标记生成函数 ---------- */

/**
 * 生成左侧时间刻度
 */
export function addLeftMarks(startKey, tabOption, step_type, endTime) {
  const marksObj = {}
  const timeCheckers = {
    'step_6min': (i) => isHourLeft(endTime, i * calcSteps(step_type)),
    'step_10min': (i) => isHourLeft(endTime, i * calcSteps(step_type)),
    'step_1h': (i) => isDayLeft(endTime, i * calcSteps(step_type)),
    'step_3h': (i) => isHourLeft_hours(endTime, i * calcSteps(step_type), 3),
    'step_6h': (i) => isHourLeft_hours(endTime, i * calcSteps(step_type), 6),
    'step_12h': (i) => isHourLeft_hours(endTime, i * calcSteps(step_type), 12),
    'step_24h': (i) => is12Hours_left(endTime, i * calcSteps(step_type)),
    'step_10days': (i) => isDayLeft_fivedays(endTime, i * calcSteps(step_type), 10),
    'step_month': (i) => isDayLeft_fivedays(endTime, i * calcSteps(step_type), 5)
  }
  
  // 默认处理函数
  const defaultChecker = (i) => isDayLeft_fivedays(endTime, i * calcSteps(step_type), 15)
  
  for (let i = 0; i <= 200; i++) {
    const checker = timeCheckers[step_type] || defaultChecker
    const [isFlag, time] = checker(i)
    
    marksObj[startKey - i] = {
      key_index: startKey - i,
      style: { color: '#fff' },
      label: isFlag === 1 ? calcMarksLeftLabel(step_type, time) : '',
      time: time,
      step_type: step_type,
      tabOption: '历史'
    }
  }
  
  return marksObj
}

/**
 * 判断是否为整点（向左添加刻度专用）
 */
export function isHourLeft(timeStr, minutesToSub) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).subtract(minutesToSub, 'minutes')
  let result = newTime.format('mm') === '00' ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为指定小时数的倍数（向左添加刻度专用）
 */
export function isHourLeft_hours(timeStr, hoursToSub, num) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).subtract(hoursToSub, 'hours')
  let result = Number(newTime.format('HH')) % num === 0 ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为指定天数的倍数（向左添加刻度专用）
 */
export function isDayLeft_fivedays(timeStr, daysToSub, num) {
  let time = moment(timeStr, "YYYY-MM-DD")
  let newTime = moment(time).subtract(daysToSub, 'days')
  let timeNum = Number(newTime.format('DD'))
  let endMonth = Number(moment(newTime).endOf('month').format('DD'))
  
  let result = 0
  if (timeNum % num === 0) {
    result = 1
  } else if (timeNum === endMonth && endMonth !== 31) {
    result = 1
  }
  
  return [result, newTime.format('YYYY-MM-DD')]
}

/**
 * 判断是否为整天（向左添加刻度专用）
 */
export function isDayLeft(timeStr, hoursToSub) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).subtract(hoursToSub, 'hours')
  let result = newTime.format('HH') === '00' ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:00')]
}

/**
 * 判断是否为12:00或00:00（向左添加刻度专用）
 */
function is12Hours_left(timeStr, hoursToSub) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).subtract(hoursToSub, 'hours')
  let hour = Number(newTime.format('HH'))
  let result = (hour === 0 || hour === 12) ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 计算左侧标签显示格式
 */
export function calcMarksLeftLabel(step_str, time) {
  const formatMap = {
    'step_6min': () => moment(time).format('HH:mm'),
    'step_10min': () => moment(time).format('HH:mm'),
    'step_1h': () => moment(time).format('MM-DD HH:mm'),
    'step_3h': () => moment(time).format('MM-DD HH:mm'),
    'step_6h': () => moment(time).format('MM-DD HH:mm'),
    'step_12h': () => moment(time).format('MM-DD HH:mm'),
    'step_24h': () => moment(time).format('MM-DD'),
    'step_10days': () => moment(time).format('MM-DD'),
    'step_month': () => moment(time).format('YYYY-MM'),
    'step_season': () => moment(time).format('YYYY-MM')
  }
  
  const formatter = formatMap[step_str]
  return formatter ? formatter() : moment(time).format('MM-DD')
}

/**
 * 生成右侧时间刻度
 */
export function addRightMarks(startKey, tabOption, step_type, startTime) {
  const marksObj = {}
  const timeCheckers = {
    'step_6min': (i) => isHourRight(startTime, i * calcSteps(step_type)),
    'step_10min': (i) => isHourRight(startTime, i * calcSteps(step_type)),
    'step_1h': (i) => isDayRight(startTime, i * calcSteps(step_type)),
    'step_3h': (i) => isThreeHours_right(startTime, i * calcSteps(step_type), 3),
    'step_6h': (i) => isThreeHours_right(startTime, i * calcSteps(step_type), 6),
    'step_12h': (i) => isThreeHours_right(startTime, i * calcSteps(step_type), 12),
    'step_24h': (i) => is12Hours_right(startTime, i * calcSteps(step_type)),
    'step_10days': (i) => isDayRight_fivedays(startTime, i * calcSteps(step_type), 10),
    'step_month': (i) => isDayRight_fivedays(startTime, i * calcSteps(step_type), 5)
  }
  
  // 默认处理函数
  const defaultChecker = (i) => isDayRight_fivedays(startTime, i * calcSteps(step_type), 15)
  
  for (let i = 0; i <= 200; i++) {
    const checker = timeCheckers[step_type] || defaultChecker
    const [isFlag, time] = checker(i)
    
    marksObj[startKey + i] = {
      key_index: startKey + i,
      style: { color: '#fff' },
      label: isFlag === 1 ? calcMarksRightLabel(step_type, time) : '',
      time: time,
      step_type: step_type,
      tabOption: tabOption
    }
  }
  
  return marksObj
}

/**
 * 判断是否为整点（向右添加刻度专用）
 */
function isHourRight(timeStr, minutesToAdd) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).add(minutesToAdd, 'minutes')
  let result = newTime.format('mm') === '00' ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为整天（向右添加刻度专用）
 */
function isDayRight(timeStr, hoursToAdd) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).add(hoursToAdd, 'hours')
  let result = newTime.format('HH') === '00' ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为12:00或00:00（向右添加刻度专用）
 */
function is12Hours_right(timeStr, hoursToAdd) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).add(hoursToAdd, 'hours')
  let hour = Number(newTime.format('HH'))
  let result = (hour === 0 || hour === 12) ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为指定小时数的倍数（向右添加刻度专用）
 */
function isThreeHours_right(timeStr, hoursToAdd, num) {
  let time = moment(timeStr, "YYYY-MM-DD HH:mm")
  let newTime = moment(time).add(hoursToAdd, 'hours')
  let result = Number(newTime.format('HH')) % num === 0 ? 1 : 0
  return [result, newTime.format('YYYY-MM-DD HH:mm')]
}

/**
 * 判断是否为指定天数的倍数（向右添加刻度专用）
 */
function isDayRight_fivedays(timeStr, daysToAdd, num) {
  let time = moment(timeStr, "YYYY-MM-DD")
  let newTime = moment(time).add(daysToAdd, 'days')
  let timeNum = Number(newTime.format('DD'))
  let endMonth = Number(moment(newTime).endOf('month').format('DD'))
  
  let result = 0
  if (timeNum % num === 0) {
    result = 1
  } else if (timeNum === endMonth && endMonth !== 31) {
    result = 1
  }
  
  return [result, newTime.format('YYYY-MM-DD')]
}

/* ---------- 公共工具函数 ---------- */

/**
 * 计算时间步数
 */
export function calcStepsCount(startTime, endTime, step_type) {
  if (!startTime || !endTime) return 0
  
  const start = moment(startTime)
  const end = moment(endTime)
  
  const timeUnits = {
    'step_6min': { unit: 'minutes', value: 6 },
    'step_10min': { unit: 'minutes', value: 10 },
    'step_1h': { unit: 'hours', value: 1 },
    'step_3h': { unit: 'hours', value: 3 },
    'step_6h': { unit: 'hours', value: 6 },
    'step_12h': { unit: 'hours', value: 12 },
    'step_24h': { unit: 'hours', value: 24 },
    'step_10days': { unit: 'days', value: 10 },
    'step_month': { unit: 'months', value: 1 },
    'step_season': { unit: 'months', value: 3 }
  }
  
  const config = timeUnits[step_type] || { unit: 'hours', value: 1 }
  const diff = end.diff(start, config.unit)
  
  return Math.ceil(diff / config.value)
}

/**
 * 调整对象键值
 */
export function adjustObjectKeys(marks, newKey) {
  if (!marks) return {}
  
  const result = {}
  Object.keys(marks).forEach(key => {
    result[parseInt(key) + newKey] = {
      ...marks[key],
      key_index: parseInt(marks[key].key_index) + newKey
    }
  })
  
  return result
}

/**
 * 获取当前位置
 */
export function getNowPosition(min, max, marks) {
  if (min === max) return 50
  return ((max - min) / 2 / (max - min)) * 100
}

/**
 * 获取时间步长文本
 */
export function getTagText(step_type) {
  const textMap = {
    'step_6min': '6分钟',
    'step_10min': '10分钟',
    'step_1h': '1小时',
    'step_3h': '3小时',
    'step_6h': '6小时',
    'step_12h': '12小时',
    'step_24h': '1天',
    'step_10days': '10天',
    'step_month': '1个月',
    'step_season': '1个季度'
  }
  
  return textMap[step_type] || '1小时'
}
